﻿/// <reference path="../GeneratedArtifacts/viewModel.js" />

myapp.AddNewPatient.Validate_execute = function (screen) {
    // get the values entered
    var PatientName = screen.PatientName;
    var PatientAge = screen.PatientAge;

    // Always show step 2 at this point
    screen.showTab("Step2");
    screen.details.displayName = "Step 2";

    // Clear ValidationMessage
    screen.ValidationMessage = "";

    if (PatientName == null || PatientAge == null) {
        screen.ValidationMessage = "Both values are required -- Click Back and try again";
        // Hide the Save button
        var SaveButton = screen.findContentItem("Save");
        SaveButton.isVisible = false;
        // Stop processing
        return;
    }

    // Check to see if this is a duplicate -- construct a query
    var filter = "(PatientName eq " + msls._toODataString(PatientName, ":String") +
        ") and (PatientAge eq " + msls._toODataString(PatientAge, ":Int32") + ")";

    // Query the database
    myapp.activeDataWorkspace.ApplicationData
        .Patients
        .filter(filter)
        .execute()
        .then(function (result) {
            // Get the results of the query
            var currentPatient = result.results[0];
            // If there are any results show duplicate record error
            if (currentPatient != null && currentPatient != 'undefined') {
                screen.ValidationMessage = "Duplicate Found -- Click Back and try again";
                // Hide the Save button
                var SaveButton = screen.findContentItem("Save");
                SaveButton.isVisible = false;
            } else {
                // There is no duplication
                screen.ValidationMessage = "Validation passed -- Save to continue";
                // Show the Save button
                var SaveButton = screen.findContentItem("Save");
                SaveButton.isVisible = true;
            }
        }, function (error) {
            alert(error);
        });
};

myapp.AddNewPatient.Back_execute = function (screen) {
    // Return to First Step
    screen.showTab("Step1");
    screen.details.displayName = "Step 1";
};

myapp.AddNewPatient.Save_execute = function (screen) {
    // Get the values entered
    var PatientName = screen.PatientName;
    var PatientAge = screen.PatientAge;
    // Set the values for the entity
    screen.Patient.PatientName = PatientName;
    screen.Patient.PatientAge = PatientAge;
    // Save and close
    myapp.commitChanges();
};
